package com.smartfactory.sail.controller;


import com.ada.base.common.ApiResponse;
import com.ada.base.common.ControllerResponse;
import com.ada.base.security.entity.SysUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smartfactory.sail.config.HeaderWrapper;
import com.smartfactory.sail.config.OperRecord;
import com.smartfactory.sail.constant.header.ListLogisticsEnum;
import com.smartfactory.sail.constant.header.OrderHTEnum;
import com.smartfactory.sail.constant.header.OrderSendGoodsEnum;
import com.smartfactory.sail.constant.header.OrderYPEnum;
import com.smartfactory.sail.dto.OrderItemsInfoDto;
import com.smartfactory.sail.entity.*;
import com.smartfactory.sail.entity.enums.ItemStatusEnum;
import com.smartfactory.sail.entity.enums.OrderItemStatusEnum;
import com.smartfactory.sail.entity.enums.OrderItemTypeEnum;
import com.smartfactory.sail.entity.enums.OrderSampleStatusEnum;
import com.smartfactory.sail.service.*;
import com.smartfactory.sail.utils.CodeUtils;
import com.smartfactory.sail.utils.DateUtils;
import com.smartfactory.sail.vo.PageParam;
import com.smartfactory.sail.vo.item.AddProjectReq;
import com.smartfactory.sail.vo.item.ProjectInfoResp;
import com.smartfactory.sail.vo.item.SampleOrderInfoResp;
import com.smartfactory.sail.vo.logistics.ListLogisticsForStorage;
import com.smartfactory.sail.vo.order.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author 王巨壁
 * @since 2019-07-24
 */
@Api(tags = "订单相关")
@RestController
@RequestMapping("/order")
public class OrderController extends ControllerResponse {
    private IOrderService iOrderService;
    private IItemService iItemService;
    private ICustService iCustService;
    private IOrderItemService iOrderItemService;
    private IContractService iContractService;
    private IUserService iUserService;
    private ILogisticsService logisticsService;

    public OrderController(IOrderService iOrderService, IItemService iItemService, ICustService iCustService, IOrderItemService iOrderItemService, IContractService iContractService, IUserService iUserService, ILogisticsService logisticsService) {
        this.iOrderService = iOrderService;
        this.iItemService = iItemService;
        this.iCustService = iCustService;
        this.iOrderItemService = iOrderItemService;
        this.iContractService = iContractService;
        this.iUserService = iUserService;
        this.logisticsService = logisticsService;
    }

    @OperRecord(content = "新增合同订单",level = 1)
    @PostMapping("addHT")
    @ApiOperation(value = "合同订单新增", notes = "合同订单新增")
    public ApiResponse<Long> addHT(@RequestBody AddContractOrderReq req) {
        return ok(iOrderService.add(req));
    }

    @OperRecord(content = "新增样品订单",level = 1)
    @PostMapping("addYP")
    @ApiOperation(value = "样品订单新增", notes = "样品订单新增")
    public ApiResponse<Long> addYP(@RequestBody AddYPOrderReq req) {
        Order order = new Order();
        order.setOrderCode(CodeUtils.creatSampleOrderCode());
        order.setSampleStatus(OrderSampleStatusEnum.DQR);
        order.setOrderType(OrderItemTypeEnum.YPDD);
        Cust cust = iCustService.queryCustByName(req.getCustName());
        if (cust == null) {
            cust = new Cust();
            cust.setEnterpriseName(req.getCustName());
            cust.setAddr(req.getCustAddr());
            cust.setId(iCustService.saveCustByOrderInfo(cust, req.getContactsName(), req.getContactInformation()));
        }
        order.setCustId(cust.getId());
        BeanUtils.copyProperties(req, order);
        BeanUtils.copyProperties(cust, order);
        Long custId = cust.getId();

        if (iOrderService.save(order)) {
            AddProjectReq addProjectReq = new AddProjectReq();
            BeanUtils.copyProperties(req, addProjectReq);
            Long itemId = iItemService.addProduct(addProjectReq, ItemStatusEnum.CYZ);
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setItemId(itemId);
            orderItem.setItemName(req.getName());
            orderItem.setOrderCode(order.getOrderCode());
//            orderItem.setUnderOrderId(CurrentUserContext.current().getId());
            //TODO temp
            orderItem.setUnderOrderId(new SysUser(8L, "王巨壁", "12345", new ArrayList<>()).getId());
            orderItem.setCustId(custId);
            orderItem.setCustName(iCustService.getById(custId).getEnterpriseName());
            orderItem.setContactsName(req.getContactsName());
            orderItem.setContactInformation(req.getContactInformation());
            orderItem.setCustAddr(req.getCustAddr());
            orderItem.setStatus(OrderItemStatusEnum.DFP);
            orderItem.setOrderType(OrderItemTypeEnum.YPDD);
            iOrderItemService.save(orderItem);

            //修改最近合作时间
            iCustService.updateCooperationTime(custId, DateUtils.getNowDate());
            return ok(order.getId());
        }
        return fail("保存失败!");
    }


    @HeaderWrapper(OrderHTEnum.class)
    @ApiOperation(value = "合同订单列表 分页 可带条件查询", notes = "合同订单列表 分页 可带条件查询")
    @PostMapping("contractOrderList/{currentPage}/{size}/{sortType}/{sortField}")
    public ApiResponse<IPage<ListHTOrderListResp>> contractOrderList(@RequestBody Map<String, Object> queryParam,
                                                                     @PathVariable("currentPage") Long currentPage,
                                                                     @PathVariable("size") Integer size,
                                                                     @PathVariable("sortType") Integer sortType,
                                                                     @PathVariable("sortField") String sortField) {

        PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
        return ok(iOrderService.getHTorderListPage(pageParam, queryParam));
    }

    @HeaderWrapper(OrderYPEnum.class)
    @ApiOperation(value = "样品订单列表 分页|currentPage|size|sortType|sortField 必传", notes = "样品订单 分页|currentPage|size|sortType|sortField 必传")
    @PostMapping("sampleOrderList/{currentPage}/{size}/{sortType}/{sortField}")
    public ApiResponse<IPage<ListYPOrderListResp>> sampleOrderList(@RequestBody Map<String, Object> queryParam,
                                                                   @PathVariable("currentPage") Long currentPage,
                                                                   @PathVariable("size") Integer size,
                                                                   @PathVariable("sortType") Integer sortType,
                                                                   @PathVariable("sortField") String sortField) {
        PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
        return ok(iOrderService.getYPorderListPage(pageParam, queryParam));
    }

    @ApiOperation(value = "样品订单详情", notes = "样品订单详情")
    @GetMapping("sampleOrderInfo/{id}")
    public ApiResponse<SampleOrderInfoResp> productInfo(@PathVariable("id") Long id) {

        QueryWrapper<OrderItem> query = new QueryWrapper<>();
        query.eq("orderId", id);
        List<OrderItem> list = iOrderItemService.list(query);
        if (list == null || list.size() == 0) {
            return fail("该订单数据异常");
        }
        OrderItem orderItem = list.get(0);
        ProjectInfoResp productInfoById = iItemService.getProductInfoById(orderItem.getItemId());
        SampleOrderInfoResp sampleOrderInfoResp = new SampleOrderInfoResp();
        BeanUtils.copyProperties(productInfoById, sampleOrderInfoResp);
        Order order = iOrderService.getById(id);
        sampleOrderInfoResp.setCustId(order.getCustId());
        sampleOrderInfoResp.setCustAddr(order.getCustAddr());
        sampleOrderInfoResp.setContactInformation(order.getContactInformation());
        sampleOrderInfoResp.setContactsName(order.getContactsName());
        sampleOrderInfoResp.setEnterpriseName(iCustService.getById(order.getCustId()).getEnterpriseName());
        return ok(sampleOrderInfoResp);
    }


    @HeaderWrapper(OrderSendGoodsEnum.class)
    @ApiOperation(value = "订销发货列表 分页|currentPage|size|sortType|sortField 必传", notes = "发货列表 分页|currentPage|size|sortType|sortField 必传")
    @PostMapping("deliverGoodsList/{currentPage}/{size}/{sortType}/{sortField}")
    public ApiResponse<IPage<ListOrderItemInfoResp>> deliverGoodsList(@RequestBody Map<String, Object> queryParam,
                                                                      @PathVariable("currentPage") Long currentPage,
                                                                      @PathVariable("size") Integer size,
                                                                      @PathVariable("sortType") Integer sortType,
                                                                      @PathVariable("sortField") String sortField) {
        PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
        return ok(iOrderService.getSendGoodsList(pageParam, queryParam));
    }
   @HeaderWrapper(ListLogisticsEnum.class)
   @ApiOperation(value = "仓库发货列表 分页|currentPage|size|sortType|sortField 必传", notes = "发货列表 分页|currentPage|size|sortType|sortField 必传")
   @PostMapping("deliverGoodsListForStorage/{currentPage}/{size}/{sortType}/{sortField}")
   public ApiResponse<IPage<ListLogisticsForStorage>> deliverGoodsListForStorage(@RequestBody Map<String, Object> queryParam,
                                                                       @PathVariable("currentPage") Long currentPage,
                                                                       @PathVariable("size") Integer size,
                                                                       @PathVariable("sortType") Integer sortType,
                                                                       @PathVariable("sortField") String sortField) {
       PageParam pageParam = new PageParam(currentPage, size, sortType, sortField);
       return ok(logisticsService.getSendGoodsList(pageParam, queryParam));
   }

    @OperRecord(content = "确认样品订单已完成",level = 1)
    @GetMapping("updateSampleOrderStatus/{orderId}")
    @ApiOperation(value = "修改样品订单状态为已完成", notes = "修改样品订单状态为已完成")
    public ApiResponse<Boolean> updateSampleOrderStatus(@PathVariable("orderId") Long orderId) {
        Order order = new Order();
        order.setId(orderId);
        order.setSampleStatus(OrderSampleStatusEnum.WC);
        iOrderService.updateById(order);
        return ok();
    }

    @GetMapping("getHTinfo/{orderId}")
    @ApiOperation(value = "获取合同订单详情", notes = "获取合同订单详情")
    public ApiResponse<Object> getHTinfo(@PathVariable("orderId") Long orderId) {

        Order byId = iOrderService.getById(orderId);
        if (byId == null) {
            return fail("该订单不存在");
        }

        HTOrderInfoResp res = new HTOrderInfoResp();

        BeanUtils.copyProperties(byId, res);
        res.setOrderId(byId.getId());
        Cust cust = iCustService.getById(byId.getCustId());
        res.setEnterpriseName(cust.getEnterpriseName());
        res.setAddr(cust.getAddr());

        Long contractId = byId.getContractId();
        Contract contract = iContractService.getById(contractId);
        if (contract != null) {
            BeanUtils.copyProperties(contract, res);
        }

        res.setUnderOrderName(iUserService.getById(res.getUnderOrderId()).getUsername());

        QueryWrapper<OrderItem> quert = new QueryWrapper<>();
        quert.eq("orderId", orderId);
        List<OrderItem> list = iOrderItemService.list(quert);
        ArrayList<OrderItemsInfoDto> resultItem = new ArrayList<>();
        for (OrderItem orderItem : list) {
            OrderItemsInfoDto htOrderInfoResp = new OrderItemsInfoDto();
            BeanUtils.copyProperties(orderItem, htOrderInfoResp);
            Item item = iItemService.getById(htOrderInfoResp.getItemId());
            htOrderInfoResp.setCode(item.getCode());
            htOrderInfoResp.setHourlyCapacity(item.getHourlyCapacity());
            htOrderInfoResp.setXiaoJi(htOrderInfoResp.getOffer() * htOrderInfoResp.getSize());
            htOrderInfoResp.setInfo(item.getInfo());
            resultItem.add(htOrderInfoResp);
        }
        res.setOrderItemsDtos(resultItem);
        return ok(res);
    }


}
